import keepAlive from '@/mixins/keepAlive.js'
import axios from "axios";
import echarts from "echarts";

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.timeout = 25000;
export default {
  mixins: [keepAlive],
  data() {
    var today = new Date();
    var yesterday = new Date();
    yesterday = yesterday.setTime(today.getTime() - 3600 * 1000 * 24);
    return {
      isReload: false,
      reportDate: null,
      maxDate_: yesterday,
      numTotal: "",
      pieChart: '',
      lineChart: '',
      reportMsg: {},
      PiePersenArr: [],
      pieActive: 5,
      limitLength: 5,
      parkIncomeDataTheads: [
      {
        propName: 'parkName',
        label: "停车场",
        width: 150
      }, {
        propName: 'subTable',
        label: "交易次数（次）",
        width: 180,
        child: [{
            propName: 'tempParkingIncomeCount',
            label: "临停",
            width: 180,
          }, {
            propName: 'monthTicketIncomeCount',
            label: "月票",
            width: 180,
          }, {
            propName: 'traderCouponIncomeCount',
            label: "优惠券",
            width: 180,
          }, {
            propName: 'shareIncomeCount',
            label: "共享",
            width: 180,
          },
          {
            propName: 'bookingIncomeCount',
            label: "预订",
            width: 100
          },
        ]
      }, {
        propName: 'subTable',
        label: "交易金额（元）",
        width: 180,
        child: [{
            propName: 'tempParkingIncomeAmount',
            label: "临停",
            width: 180,
          }, {
            propName: 'monthTicketIncomeAmount',
            label: "月票",
            width: 180,
          }, {
            propName: 'traderCouponIncomeAmount',
            label: "优惠券",
            width: 180,
          }, {
            propName: 'shareIncomeAmount',
            label: "共享",
            width: 180,
          },
          {
            propName: 'bookingIncomeAmount',
            label: "预订",
            width: 100
          },
        ]
      }],
      parkIncomeData: {
        tbBody: [],
        fixedCols: 2,
        rp: 10,
        page: 1,
        total: 0,
      },
      // 指定图表的配置项和数据
      pieOption: {
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        color: ['#EA7D5E', '#fd87ab', '#11abff', '#ffdf33', '#968ade', '#5174DE'],
        series: [{
          name: '金额组成',
          type: 'pie',
          radius: ['38%', '50%'],
          avoidLabelOverlap: false,
          label: {
            normal: {
              formatter: '{d}%',
            },
            emphasis: {
              show: true,
              textStyle: {
                fontSize: '12',
                fontWeight: 'bold'
              }
            }
          },

          labelLine: {
            normal: {
              show: true
            }
          },
          data: [{
              value: 0,
              name: '临停'
            },
            {
              value: 0,
              name: '月票'
            },
            {
              value: 0,
              name: '优惠券'
            },
            {
              value: 0,
              name: '共享'
            },
            {
              value: 0,
              name: '预订'
            }
          ]
        }]
      },
      lineOption: {
        grid: {
          top: 25,
          left: 0,
          right: 0,
          containLabel: true,
        },
        legend: {
          data: ['收入：', '环比：'],
          bottom: 5,
        },
        color: ['#E1D8D4', '#5174DE', '#EB9643', '#ffdf33', '#968ade'],
        tooltip: {
          trigger: 'axis',
          formatter: function (tipData) {
            return '<div>' + '<p>' + tipData[0].seriesName + tipData[0].value + '</p>' + '<p>' + tipData[1].seriesName + (tipData[1].value * 1).toFixed(2) + '%' + '</p>' + '</div>'
          },
          axisPointer: {
            label: {
              backgroundColor: '#283b56'
            }
          }
        },
        xAxis: [{
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        }],
        yAxis: [{
            type: 'value',
            axisLabel: {
              interval: 0,
              margin: 10,
              formatter: function (value, index) {
                if (value > 10000) {
                  return ((value / 100) / 100) + "W";
                } else {
                  return value;
                }
              }
            },
          },
          {
            axisLabel: {
              formatter: '{value}%',
              interval: 0,
              margin: 10,
            },
            splitLine: {
              show: false
            },
          }
        ],
        series: [{
          name: "收入：",
          data: [120, 20300, 150, 30, 70, 110, 130],
          type: 'bar',
        }, {
          yAxisIndex: 1,
          name: "环比：",
          data: [32, 27, 55, 85, 34, 41, 23],
          type: 'line',
        }]
      }
    }
  },
  mounted() {
    // 基于准备好的dom，初始化echarts实例
    // this.pieChart = echarts.init(document.getElementById('pieBox'));
    // this.lineChart = echarts.init(document.getElementById('lineBox'));
  },

  methods: {
    disabledDate(time) {
      // return time.getTime() >= new Date().getTime(); //今天日期可以选
      return time.getTime() > Date.now() - 8.64e7; //今天日期不可选
    },
    //重新生成
    reBuild(){
      let url = '/report/incomeSummaryReport/reStatReport.do',reportDimension = this.searchList[0].value, date = this.searchList[1].value
      let type = ''
      let dateStr = ''
      let yearStr = date.getFullYear() 
      let monthStr = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1;
      let dayStr = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
      if(reportDimension=='0'){
        dateStr = yearStr+'-'+monthStr+'-'+dayStr
        type = 'date'
      }else if(reportDimension=='1'){
        dateStr = yearStr+'-'+monthStr
        type = 'month'
      }
      if(!this.otherParams.parkIds){
        this.showToast('请先选择一个停车场', 0, 1500)
        return
      }
      let params = {
        parkId: this.otherParams.parkIds,
        date: dateStr,
        type: type
      }
      API.fetchGet(url,params).then(res=>{
        if(res.status==1){
          this.searchParams.parkId =  params.parkId
          this.searchParams.statDate = dateStr
          this.searchParams.reportDimension = reportDimension
          let aparams = {
            statDate: dateStr,
            parkId: params.parkId,
            reportDimension: reportDimension
          }
          this.confirmSearch(aparams)
        }
      },err=>{})
    },
    getList() {
      let _this = this;
      var dayMax = moment(_this.searchParams.dateFromTo).format("YYYY-MM-DD 00:00:00");
      var dayMax_date = new Date(dayMax);
      if (dayMax_date.getTime() <= _this.maxDate_) {
        if (_this.pieChart) {
          echarts.dispose(_this.pieChart);
        }
        if (_this.lineChart) {
          echarts.dispose(_this.lineChart);
        }
        _this.pieChart = echarts.init(document.getElementById('pieBox'));
        _this.lineChart = echarts.init(document.getElementById('lineBox'));
        _this.getReportData();
        _this.getPageData();
      } else {
        _this.showToast("请选择今天之前的日期", 1, 1500);
      }
    },
    // 初始化line的数据且一次初始化之后不改变了
    initLineData() {
      this.lineChart = echarts.init(document.getElementById('lineBox'));
      let _this = this;
      let timeX = [],
        dataInCome = [],
        HB = [],
        TB = [];
      _this.reportMsg.trendList.forEach((element, index) => {
        if (element.reportDate) {
          let date = new Date(element.reportDate);
          //获取一个时间对象
          //  date.getMonth(); // 获取月份(0-11,0代表1月,用的时候记得加上1)
          //  date.getDate(); // 获取日(1-31)
          if(_this.searchParams.reportDimension==1){ //月报
            timeX.unshift(date.getMonth() + 1 + "月" );
          }else{ //日报
            timeX.unshift(date.getMonth() + 1 + "-" + date.getDate());
          }
          dataInCome.unshift(element.tradeAmount ? element.tradeAmount.toFixed(2) : 0);
          HB.unshift(element.tradeAmountHB ? element.tradeAmountHB * 100 : 0);
          TB.unshift(element.tradeAmountTB ? element.tradeAmountTB * 100 : 0);
        }
      });
      _this.lineOption.xAxis[0].data = timeX;
      _this.lineOption.series[0].data = dataInCome;
      // _this.lineOption.series[1].data = TB;
      _this.lineOption.series[1].data = HB;
      _this.lineChart.setOption(_this.lineOption);
    },
    // 初始化饼图时触发函数
    changePieData(type) {
      // 基于准备好的dom，初始化echarts实例
      this.pieChart = echarts.init(document.getElementById('pieBox'));
      let _this = this;
      let index = 0
      _this.pieActive = type;
      if (_this.pieActive == 5) {
        // 获取总金额的组成份额
        _this.pieOption.series[0].data = [{
            value: _this.reportMsg.tempParkingIncomeAmount,
            labelLine: {
              length: (index++) * 10
            },
            name: '临停'
          },
          {
            value: _this.reportMsg.monthTicketIncomeAmount,
            labelLine: {
              length: (index++) * 10
            },
            name: '月票'
          },
          {
            value: _this.reportMsg.traderCouponIncomeAmount,
            labelLine: {
              length: (index++) * 10
            },
            name: '优惠券'
          },
          {
            value: _this.reportMsg.shareIncomeAmount,
            labelLine: {
              length: (index++) * 10
            },
            name: '共享'
          },
          {
            value: _this.reportMsg.bookingIncomeAmount,
            labelLine: {
              length: (index++) * 10
            },
            name: '预订'
          }
        ];
        _this.pieChart.setOption(_this.pieOption);
        _this.calcuPiePersen()
      } else {
        // 获取其他组成的组成份额
        if (_this.reportDate) {
          _this.changeCallBack(type);
        }
      }
    },
    handleSearchChange2(item) {
      switch (item.name) {
        case 'reportDimension':
          this.changeReportDimension2(item);
          break;
      }
    },
    changeReportDimension2(item) {
      let value = item.value,
        ThisSearchItem = this.searchList[1];
        var today = new Date(moment().subtract(1, 'days').format('YYYY-MM-DD 00:00:00'));
        var month = new Date(moment().subtract(1, 'months').format('YYYY-MM-DD 00:00:00'));
      switch (value) {
        case '0':
          ThisSearchItem.type = 'datePicker';
          ThisSearchItem.flag = 'date';
          ThisSearchItem.pickerType = 'date';
          ThisSearchItem.isSingle = true;
          ThisSearchItem.format = 'yyyy-MM-dd';
          ThisSearchItem.value = today;
          break;
        case '1':
          ThisSearchItem.style = {
            width: '185px'
          };
          ThisSearchItem.type = 'datePicker';
          ThisSearchItem.flag = 'month';
          ThisSearchItem.pickerType = 'month';
          ThisSearchItem.isSingle = true;
          ThisSearchItem.format = 'yyyy-MM';
          ThisSearchItem.value = month;
          break;
      }
    },
    calcuPiePersen() {
      let total = 0;
      let _this = this;
      _this.PiePersenArr = [];
      _this.pieOption.series[0].data.forEach(element => {
        total += element.value
      });
      _this.numTotal = total;
      _this.pieOption.series[0].data.forEach(element => {
        let value = total == 0 ? "0%" : ((element.value * 100 / total).toFixed(2)) + "%";
        _this.PiePersenArr.push(value);
      });
    },
    //重置数据为空的状态
    onError() {
      this.reportMsg.tradeAmount = 0;
      this.reportMsg.tradeAmountHB = 0;
      this.reportMsg.tradeCount = 0;
      this.reportMsg.tradeCountHB = 0;
      this.reportMsg.totalParkingCount = 0;
      this.reportMsg.parkVelocity = 0;
      this.lineOption.series[0].data = [];
      this.pieOption.series[0].data = [];
    },
    //点击具体的详情时展示 饼图不同的数据
    changeCallBack(type) {
      let _this = this;
      let params = {
        rd: _this.searchParams.reportDimension ? _this.searchParams.reportDimension : '0',
        fromDate: moment(_this.searchParams.dateFromTo).format("YYYY-MM-DD 00:00:00"),
        toDate: moment(_this.searchParams.dateFromTo).format("YYYY-MM-DD 23:59:59"),
        incomeType: type,
      };
      if(_this.otherParams && _this.otherParams.parkIds){
        params.query_parkId = _this.otherParams.parkIds
      }
      axios.post('/report/incomeSummaryReport/incomeSummaryItemList.do', params)
        .then(function (response) {
          let res = response.data.data;
          if (res.length > 0) {
            let dataArr = [];
            let total = 0;
            // 计算总金额
            res.forEach(element => {
              total += element.value
            });
            _this.numTotal = total;
            // 大于limitLength个 -先执行排序操作
            if (res.length > _this.limitLength) {
              function compare(val1, val2) {
                return val2.value - val1.value;
              };
              res.sort(compare);
            }
            res.forEach((element, index) => {
              if (index + 1 > _this.limitLength) {
                // 数组大于limitLength的归于 “其他”  第六名
                if (index == _this.limitLength) {
                  let dataObj = {};
                  dataObj.name = "其他";
                  dataObj.value = 0;
                  dataObj.labelLine = {
                    length: index * 10
                  };
                  dataArr.push(dataObj)
                }
                dataArr[_this.limitLength].value += element.value;
              } else {
                // 前五名
                let dataObj = {};
                dataObj.name = element.itemName;
                dataObj.value = element.value;
                dataObj.labelLine = {
                  length: index * 10
                };
                dataArr.push(dataObj)
              }
            });

            _this.pieOption.series[0].data = dataArr;
            _this.pieChart.setOption(_this.pieOption);
            _this.calcuPiePersen()
          } else {
            _this.pieOption.series[0].data = []
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getReportData() {
      let _this = this;
      let params = {
        rd: _this.searchParams.reportDimension ? _this.searchParams.reportDimension : '0',
        fromDate: moment(_this.searchParams.dateFromTo).format("YYYY-MM-DD 00:00:00"),
        toDate: moment(_this.searchParams.dateFromTo).format("YYYY-MM-DD 23:59:59"),
        query_parkId: _this.otherParams.parkIds
      };
      axios.post('/report/incomeSummaryReport/incomeSummary.do', params)
        .then(function (response) {
          _this.reportMsg = response.data.data;
          if (!response.data.data.reportDate) {
            //返回值找不到数据，收入构成的按钮不允许向后台查询数据
            _this.reportDate = null;
          } else {
            _this.reportDate = response.data.data.reportDate;
          }
          _this.changePieData(5);
          if(_this.reportMsg.trendList!=null){
            _this.initLineData();
          }
        })
        .catch(function (error) {
          _this.onError();
          console.log(error);
        });
    },
    getPageData() {
      let _this = this;
      let params = {
        rd: _this.searchParams.reportDimension ? _this.searchParams.reportDimension : '0',
        rp: _this.parkIncomeData.rp,
        fromDate: moment(_this.searchParams.dateFromTo).format("YYYY-MM-DD 00:00:00"),
        toDate: moment(_this.searchParams.dateFromTo).format("YYYY-MM-DD 23:59:59"),
        page: _this.parkIncomeData.page,
        query_parkId: _this.otherParams.parkIds
      };
      // axios.post('http://172.18.30.5:8080/mgr-weixin/manage/report/incomeSummaryParkDataList.do', params)
      axios.post('/report/incomeSummaryReport/incomeSummaryParkDataList.do', params)
        .then(function (response) {
          _this.parkIncomeData.tbBody = response.data.data.rows ? response.data.data.rows : [];
          _this.parkIncomeData.total = response.data.data.total;
          _this.parkIncomeData.rp = response.data.data.rp;
          _this.parkIncomeData.page = response.data.data.page;
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.parkIncomeData.rp = val;
      this.getPageData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.parkIncomeData.page = val;
      this.getPageData();
    }

  },

  computed: {
    reloadTable () {
      return this.$store.state.menu.reloadTable
    }
  },

  watch: {
    reloadTable (Val) {
      this.isReload = true
      this.$nextTick(() => {
        this.isReload = false
        this.getList()
      })
    }
  },

  activated () {
    this.getList()
  },

  filters: {
    numFilter: function (val) {
      // val = val * 1098667;
      if (val && val > 10000) {
        // console.log(val, (parseInt(val / 100) / 100) + 'W')
        return (parseInt(val / 100) / 100) + 'W'
      } else {
        return val
      }
    },
    toFixed: function (val) {
      return (val * 100).toFixed(2) + "%"
    }
  }
}
